<template>
  <div class="mid-group">
    <div v-for="(item, index) in list" :key="index" class="box" @drop="drop($event, index)" @dragover.prevent draggable>
      {{ index }}
      <component
        v-for="(subItem, subIndex) in item"
        :key="`subIndex${subIndex}`"
        :is="subItem.name"
        :number="subIndex"
        :propValue="subItem.style"
      />
    </div>
  </div>
</template>
<script lang="ts">
  // 在vue2中 data 在vue3中使用 reactive代替
  import { reactive, watch, toRefs } from 'vue'
  import { useRouter } from 'vue-router'
  import buttonComponents from './button.vue'
  import ButtonStyle from './module/button'
  // import { cloneDeep } from 'lodash'
  export default {
    // 组件注册
    components: { buttonComponents },
    props: {
      componentList: {
        type: Array,
        default: () => {
          return new Array<Array<any>>()
        },
      },
    },
    // watch: {
    //   'props.componentList': {
    //     handler(val, oldVal) {
    //       console.log('book list changed')
    //     },
    //     deep: true,
    //   },
    // },
    // setup相当于vue2.0的 beforeCreate和 created，是vue3新增的一个属性，所有的操作都在此属性中完成
    setup(props: any, context: any) {
      // 通过reactive 可以初始化一个可响应的数据，与Vue2.0中的Vue.observer很相似
      const state = reactive({
        list: new Array<any>(),
      })
      watch(
        () => [props.componentList],
        ([newValue], [oldValue]) => {
          console.log(newValue)
          state.list = newValue
        },
        {
          deep: true,
        }
      )
      // DragEvent 本来使用这个模型的但是有的东西有还会报错、所以换其他的了
      const drop = (event: any, index: number) => {
        const arr = state.list
        const obj = {
          name: 'buttonComponents',
          style: new ButtonStyle(),
        }
        //算出鼠标相对元素的位置
        const disX = event.clientX - event.offsetX
        const disY = event.clientY - event.offsetY
        const subIndex = event?.dataTransfer.getData('my-number')
        if (event.dataTransfer) {
          obj.name = event?.dataTransfer.getData('my-info')
          obj.style.top = `${event?.clientX - disX}px`
          obj.style.left = `${event?.clientX - disY}px`
        }
        state.list[index][subIndex] = obj
      }
      return {
        ...toRefs(state),
        drop,
      }
    },
  }
</script>
<style lang="scss" scoped>
  .box {
    position: relative;
    height: 100px;
    border: 10px rgba(143, 139, 139, 0.89);
    // overflow: hidden;
  }
</style>
